<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <my-component id="com"></my-component>
</body>
<script>
    //生成Shadow Root，可以在上面添加DOM节点
    class MyComponent extends HTMLElement{
        constructor() {
            super();
            let shadow = this.attachShadow({
                mode:'open'//是close时不允许外部js访问shadowRoot
            })

            let divnode = document.createElement('div');
            divnode.style.width = '100px';
            divnode.style.height = '100px';
            divnode.style.backgroundColor = '#707f57';
            
            let imgnode = document.createElement('img');
            imgnode.src = 'https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/09ac1ee65db54f23a40d7a564a493a77~tplv-k3u1fbpfcp-zoom-in-crop-mark:4536:0:0:0.awebp?';
            imgnode.id = 'img1';

            imgnode.style.width = '800px';
            imgnode.style.border = '1px';
            imgnode.style.borderColor = 'red';

            shadow.appendChild(divnode);
            shadow.appendChild(imgnode);
        }
    }

    customElements.define('my-component',MyComponent);

    let com = document.querySelector('#com');
    let comRoot = com.shadowRoot;

    com.onclick = function() {
        console.dir(comRoot)
    }

    console.log(comRoot.querySelector('#img1'));//通过shadowRoot可以访问到组件中的元素
</script>
</html>